#!/usr/bin/env bash

set -eu -o pipefail

source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../utils.sh"

: "${ASDF_NODEJS_NODEBUILD_HOME=$ASDF_NODEJS_PLUGIN_DIR/.node-build}"
: "${ASDF_NODEJS_NODEBUILD_REPOSITORY=https://github.com/nodenv/node-build.git}"
: "${ASDF_NODEJS_NODEBUILD_BRANCH=main}"

ensure_updated_project() {
  local pull_exit_code=0

  if ! [ -d "$ASDF_NODEJS_NODEBUILD_HOME" ]; then
    printf "Cloning node-build...\n"
    git clone "$ASDF_NODEJS_NODEBUILD_REPOSITORY" "$ASDF_NODEJS_NODEBUILD_HOME" --branch "$ASDF_NODEJS_NODEBUILD_BRANCH"
  else
    printf "Trying to update node-build..."
    git -C "$ASDF_NODEJS_NODEBUILD_HOME" fetch origin "$ASDF_NODEJS_NODEBUILD_BRANCH" >&2 || pull_exit_code=$?
    git -C "$ASDF_NODEJS_NODEBUILD_HOME" checkout "$ASDF_NODEJS_NODEBUILD_BRANCH" >&2 || true
    git -C "$ASDF_NODEJS_NODEBUILD_HOME" merge --ff-only "origin/$ASDF_NODEJS_NODEBUILD_BRANCH" >&2 || true

    if [ "$pull_exit_code" != 0 ]; then
      printf "$(colored $RED ERROR): Pulling the node-build repository exited with code %s\n" "$pull_exit_code"
      printf "Please check if the git repository at %s doesn't have any changes or anything\nthat might not allow a git pull\n" "$ASDF_NODEJS_NODEBUILD_HOME"
      exit $pull_exit_code
    fi

    # For some time, asdf-core was cleaning up the node-build directory by accident
    # This is a workaround to restore the files that were deleted
    if ! [ -f "$ASDF_NODEJS_NODEBUILD_HOME/bin/nodebuild" ]; then
      git -C "$ASDF_NODEJS_NODEBUILD_HOME" checkout HEAD . >&2
    fi

    printf " ok\n"
  fi
}

ensure_updated_project
